<template>
  <div class="app-container p-6">
    <div class="card">
      <div class="d-flex justify-between items-center mb-4">
        <div class="text-primary" style="font-weight:600;">系统日志</div>
        <div class="d-flex" style="gap:8px;">
          <el-button :icon="Download" @click="handleExport" v-permission="'security:log:export'">导出</el-button>
          <el-button :icon="Delete" type="danger" @click="handleClear" v-permission="'security:log:clear'">
            清空日志
          </el-button>
        </div>
      </div>

      <div class="bg-panel radius-lg p-4 mb-4">
        <el-form :model="queryParams" :inline="true">
          <el-form-item label="操作模块">
            <el-input v-model="queryParams.module" placeholder="请输入操作模块" clearable />
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="queryParams.operation" placeholder="请选择操作类型" clearable>
              <el-option label="登录" value="LOGIN" />
              <el-option label="登出" value="LOGOUT" />
              <el-option label="新增" value="CREATE" />
              <el-option label="修改" value="UPDATE" />
              <el-option label="删除" value="DELETE" />
              <el-option label="查询" value="QUERY" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作人员">
            <el-input v-model="queryParams.username" placeholder="请输入操作人员" clearable />
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="bg-panel radius-lg p-0">
        <el-table
          v-loading="loading"
          :data="logList"
          row-key="id"
          border
          style="width: 100%"
        >
          <el-table-column prop="module" label="操作模块" min-width="120" />
          <el-table-column prop="operation" label="操作类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getOperationTag(row.operation)" size="small">
                {{ getOperationText(row.operation) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="method" label="请求" min-width="160" />
          <el-table-column prop="username" label="操作人员" width="120" />
          <el-table-column prop="ip" label="IP地址" width="130" />
          <el-table-column prop="duration" label="耗时(ms)" width="100" align="center" />
          <el-table-column prop="createTime" label="操作时间" width="200">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                :icon="View"
                @click="handleView(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="d-flex justify-between items-center p-4">
          <el-pagination
            v-show="total > 0"
            :current-page="queryParams.current"
            :page-size="queryParams.size"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 日志详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="日志详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="操作模块">{{ currentLog.module }}</el-descriptions-item>
          <el-descriptions-item label="操作类型">{{ getOperationText(currentLog.operation) }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">{{ currentLog.method }}</el-descriptions-item>
          <el-descriptions-item label="操作人员">{{ currentLog.username }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
          <el-descriptions-item label="耗时">{{ currentLog.duration }}ms</el-descriptions-item>
          <el-descriptions-item label="操作时间" :span="2">{{ currentLog.createTime }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">请求参数</el-divider>
        <pre class="bg-subtle radius-md p-3" style="max-height:200px; overflow:auto; font-size:12px; line-height:1.4; border:1px solid var(--border-light)">{{ currentLog.params || '无' }}</pre>

        <el-divider content-position="left">响应结果</el-divider>
        <pre class="bg-subtle radius-md p-3" style="max-height:200px; overflow:auto; font-size:12px; line-height:1.4; border:1px solid var(--border-light)">{{ currentLog.result || '无' }}</pre>
      </div>
      
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Download,
  Delete,
  View
} from '@element-plus/icons-vue'
import type { OperationLog } from '@/types/system'
import { securityApi } from '@/api/security'
import { formatDate } from '@/utils/date'

// 响应式数据
const loading = ref(false)
const logList = ref<OperationLog[]>([])
const total = ref(0)
const detailVisible = ref(false)
const currentLog = ref<OperationLog>({} as OperationLog)
const dateRange = ref<string[]>([])

const queryParams = reactive({
  current: 1,
  size: 20,
  module: '',
  operation: '',
  username: '',
  startTime: '',
  endTime: ''
})

// 方法
const getList = async () => {
  loading.value = true
  try {
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = ''
      queryParams.endTime = ''
    }

    const params: any = {
      current: queryParams.current,
      size: queryParams.size,
      module: queryParams.module || undefined,
      operation: queryParams.operation || undefined,
      username: queryParams.username || undefined,
      startDate: queryParams.startTime || undefined,
      endDate: queryParams.endTime || undefined
    }
    const resp = await securityApi.getOperationLogs(params)
    logList.value = (resp?.data?.data || []) as OperationLog[]
    total.value = Number(resp?.data?.total || 0)
  } catch (error) {
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

const getOperationText = (operation: string) => {
  const operationMap: Record<string, string> = {
    'LOGIN': '登录',
    'LOGOUT': '登出',
    'CREATE': '新增',
    'UPDATE': '修改',
    'DELETE': '删除',
    'QUERY': '查询'
  }
  return operationMap[operation] || operation
}

const getOperationTag = (operation: string) => {
  const tagMap: Record<string, string> = {
    'LOGIN': 'success',
    'LOGOUT': 'info',
    'CREATE': 'primary',
    'UPDATE': 'warning',
    'DELETE': 'danger',
    'QUERY': ''
  }
  return tagMap[operation] || 'info'
}

const handleQuery = () => {
  queryParams.current = 1
  getList()
}

const resetQuery = () => {
  queryParams.module = ''
  queryParams.operation = ''
  queryParams.username = ''
  dateRange.value = []
  queryParams.current = 1
  getList()
}

const handleSizeChange = (size: number) => {
  queryParams.size = size
  getList()
}

const handleCurrentChange = (current: number) => {
  queryParams.current = current
  getList()
}

const handleView = (row: OperationLog) => {
  currentLog.value = row
  detailVisible.value = true
}

const handleExport = () => {
  const params: any = {}
  if (dateRange.value && dateRange.value.length === 2) {
    params.startDate = dateRange.value[0]
    params.endDate = dateRange.value[1]
  }
  if (queryParams.module) params.module = queryParams.module
  if (queryParams.operation) params.operation = queryParams.operation
  if (queryParams.username) params.username = queryParams.username
  securityApi.exportOperationLogs(params)
}

const formatTime = (time: string) => {
  return formatDate(time)
}

const handleClear = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有操作日志吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      await securityApi.clearOperationLogs()
      ElMessage.success('清空日志成功')
      getList()
    } catch (e) {
      ElMessage.error('清空日志失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空日志失败')
    }
  }
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped></style>
